package com.example.lym.syappandroid;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.List;

import model.Alarm;
import model.AlarmAdapter;
import model.User;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import regular.IRegulation;

public class AlarmActivity extends AppCompatActivity {

    private int u_id;
    private List<Alarm> alarmList = new ArrayList<>();
    private ListView lv_alarms;
    private TextView tv_alarm_all;
    private TextView tv_alarm_task;
    private ImageView iv_alarm_logout;
    private ImageView iv_totask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm);
        ActivityCollector.addActivity(AlarmActivity.this);
        Init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(AlarmActivity.this);
    }

    /**
     * 初始化控件并挂载事件
     */
    private void Init() {
        //根据User获取alarmList
        InitAlarmList();
        //初始化切换标签
        tv_alarm_all = (TextView) findViewById(R.id.tv_alarm_all);
        tv_alarm_task = (TextView) findViewById(R.id.tv_alarm_task);
        tv_alarm_task.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AlarmActivity.this,TaskalarmActivity.class);
                startActivity(intent);
            }
        });
        //TODO 初始化任务-提醒切换标签
        iv_totask = (ImageView)findViewById(R.id.iv_totask);
        iv_totask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AlarmActivity.this,TaskActivity.class);
                startActivity(intent);
            }
        });
        //初始化退出标签
        iv_alarm_logout = (ImageView) findViewById(R.id.iv_alarm_logout);
        iv_alarm_logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //退出事件
                ActivityCollector.finishAll();
            }
        });
    }

    /**
     * 根据alarmList展示List
     */
    private void InitAlarms(){
        runOnUiThread(new Runnable() {
            @SuppressWarnings("Since15")
            @Override
            public void run() {
                lv_alarms = (ListView) findViewById(R.id.lv_alarms);
                alarmList.sort(new Comparator<Alarm>() {
                    @Override
                    public int compare(Alarm o1, Alarm o2) {
                        return o2.getA_time().compareTo(o1.getA_time());
                    }
                });
                AlarmAdapter adapter = new AlarmAdapter(AlarmActivity.this,R.layout.alarm_item,alarmList);
                lv_alarms.setAdapter(adapter);
                lv_alarms.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Alarm alarm = alarmList.get(position);
                        Intent intent = new Intent(AlarmActivity.this,ShowalarmActivity.class);
                        intent.putExtra("a_id",alarm.getA_id());
                        startActivity(intent);
                    }
                });
            }
        });
    }

    /**
     * 初始化列表和AlarmList
     */
    private void InitAlarmList(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder().add("u_id", User.getU_id()+"").build();
                    Request request = new Request.Builder().url(IRegulation.URL+"alarm/getlistbyuserid").post(requestBody).build();
                    Response response = client.newCall(request).execute();
                    String str = response.body().string();
                    JSONObject jsonObject = JSONObject.fromObject(str);
                    //验证jsonObject的code

                    if(IRegulation.FAILED.equals(jsonObject.getString("resultCode"))){//失败
                        Log.e("LYM","获取用户提醒列表失败");
                    }else if(IRegulation.LACKACCESS.equals(jsonObject.getString("resultCode"))){
                        Log.e("LYM","用户无权限");
                    }else if(IRegulation.SUCCESS.equals(jsonObject.getString("resultCode"))){
                        //获取数据
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        for(int i=0;i<jsonArray.size();i++){
                            JSONObject temp = jsonArray.getJSONObject(i);
                            Alarm alarm = new Alarm(temp.getInt("a_isread")==1,temp.getInt("a_id"),temp.getString("a_name"), temp.getString("a_time")
                                    ,temp.getInt("u_id"),temp.getInt("t_id"),temp.getString("a_detail"),temp.getInt("a_ispush")==1);
                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            if(alarm.isA_ispush())
                                alarmList.add(alarm);
                        }
                    }
                    //初始化列表
                    InitAlarms();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ParseException e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
